package com.ruoyi.common.security.interceptor;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


public class TenantIdInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String tenantId = request.getHeader(SecurityConstants.AUTH_TENANT_ID);

        if (StringUtils.isEmpty(tenantId)) {
            tenantId = MDC.get(SecurityConstants.AUTH_TENANT_ID);
        }

        if (StringUtils.isEmpty(tenantId)
                && StringUtils.isNotEmpty(SecurityUtils.getToken())) {
            String token = SecurityUtils.getToken();
            tenantId = JwtUtils.getTenantId(token);
            MDC.put(SecurityConstants.TENANT_ID, tenantId);

        }

        if (StringUtils.isNotEmpty(tenantId)) {
            MDC.put(SecurityConstants.AUTH_TENANT_ID, tenantId);
        } else {
            System.out.println("requestUrl:[{" + request.getRequestURI() + "}],tenantId not found!!!");
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.clear();
    }
}
